package project.web;

import Utils.db.DruidUtils;
import Utils.db.JdbcUtilsStatic;
import project.pojo.User;
import project.service.UserService;
import project.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

@Deprecated()
@WebServlet(name = "RegistServlet", value = "/RegistServlet")
public class RegistServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Connection conn = DruidUtils.getInstance("jdbc_book.properties").getConnection();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");
        String repwd = request.getParameter("repwd");

        // 检查验证码是否正确（写死，要求验证码为"abcde"）
        if (code.equalsIgnoreCase("abcde")) {
            System.out.println("验证码[" + code + "]正确！");

            try {
                if (userService.exists( username)) {
                    request.setAttribute("msg", "用户名已经存在！");
                    request.getRequestDispatcher("pages/user/regist.jsp").forward(request, response);
                } else {
                    userService.register( new User(username, password, email));
                    request.getRequestDispatcher("pages/user/regist_success.jsp").forward(request, response);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            request.setAttribute("msg", "验证码错误！");
            request.setAttribute("username", username);
            request.setAttribute("email", email);
            request.setAttribute("password", password);
            request.setAttribute("repwd", repwd);
            request.getRequestDispatcher("pages/user/regist.jsp").forward(request, response);
        }
    }

    @Override
    public void destroy() {
        JdbcUtilsStatic.close(conn);
        super.destroy();
    }
}
